package com.tongqin.distributed;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.util.concurrent.CountDownLatch;

/**
 * @author yuantongqin
 * @date 2018/7/12 下午3:33
 */
public class WatcherDemo {

    public static void main(String[] args) {
        try {
            CountDownLatch countDownLatch = new CountDownLatch(1);
            ZooKeeper zooKeeper = new ZooKeeper("172.16.233.128:2181", 4000, new Watcher() {
                @Override
                public void process(WatchedEvent watchedEvent) {
                    //这个是连接成功的状态
                    System.out.println("状态："+watchedEvent.getType());
                    if(watchedEvent.getState()==Event.KeeperState.SyncConnected){
                        countDownLatch.countDown();
                    }
                }
            });
            countDownLatch.await();

            zooKeeper.create("/zk-change-exist","0".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);

            System.out.println(zooKeeper.getState());
            //因为watcher是一次性连接的，如何要一直监听，需要循环设置
            Stat stat = zooKeeper.exists("/zk-change-exist", new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                    System.out.println(event.getType() + "==我们不一样==" + event.getPath());
                    try {
                        //这里默认事前是zookeeper实例里的watcher全局事件
                        zooKeeper.exists(event.getPath(), true);
                    } catch (KeeperException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            stat = zooKeeper.setData("/zk-change-exist", "2".getBytes(), stat.getVersion());

            Thread.sleep(1000);
            zooKeeper.delete("/zk-change-exist",stat.getVersion());

            zooKeeper.close();

        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
